<!-- 
    ai写作助手 - 导入视频组数据 组件
-->
<script setup>
import { DeleteOutlined, EditOutlined } from "@ant-design/icons-vue";
import { ref, reactive, computed, nextTick } from "vue";
import EditTitleComponent from "./dialog/EditTitleComponent.vue";
import { nanoid } from "nanoid";
import { message } from "ant-design-vue";
import {
  base_data,
  subtitleHeightratio,
  titleHeightratio,
  textSubtitleHeight,
  getTextWidthUsingCanvas,
  xLocation,
  resetXY,
  sizeData,
  splitTextAndRemoveCommas,
  yOffset,
  addNewlineAfterPunctuation,
  getAllTemplateAudio,
  getGlobalSubtitleAudio,
} from "@/views/shotstack/MuseMixedCut/utools/index.js";
// 素材库
import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";

import { useStore } from "vuex";

import utils from '@/common/utils/utils'
// 充值弹窗
import vipModal from '@/socialMedia/Vip/vipModal.vue'
const vipModalRef = ref(null)
const vipVisible = ref(false)

const store = useStore();

const emit = defineEmits([
  "updateStep:step",
  "updateAiData:data",
  "updateStepThree:data",
  "emitArr:data",
]);

const props = defineProps({
  // 素材库
  isQuanJU: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  // 是否是脚本
  isScript: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  initData: {
    type: Object || null,
    default: () => {
      return null;
    },
  },
  // 存储当前导入的数据是哪种类型 0-分镜头文本，1-全局文本
  type: {
    type: Number || String,
    default: () => {
      return "";
    },
  },
});

// 从仓库中拿到的混剪整体数据
const VideoMashup = computed(() => {
  return store.state.shotstack.VideoMashup;
});

// 花字列表
const FlowerArr = computed(() => {
  return store.state.shotstack.FlowerArr;
});

// 获取随机的花字样式
const getFlower = () => {
  return [
    FlowerArr.value[Math.floor(Math.random() * 5)],
    FlowerArr.value[Math.floor(Math.random() * FlowerArr.value.length)],
  ];
};

const EditTitleComponentRef = ref(null);

const state = reactive({
  materiallibraryShow: false,
  spinning: false,

  // 正在获取音频中
  getVoiceLoding: false,
  arr: [  ],
});
const editTitle = (i) => {
  console.log(i, "编辑的项");
  EditTitleComponentRef.value.showModal(i);
};

const openType = ref({
  index: 0,
  item_index: 0,
});
// 打开素材库
const openMaterial = (type) => {
  openType.value = type;
  state.materiallibraryShow = true;
};

// 素材选择回调
const closeChooseMaterial = (data) => {
  if (data && data.material_content !== "") {
    // debugger
    state.arr[openType.value.index].subtitle_text_block[
      openType.value.item_index
    ].text = data.material_content;
  }
  state.materiallibraryShow = false;
};

const cloneText = ref("");
// 打开文本项的编辑框
const showTextArea = (item, item_index, parent_index) => {
  // 遍历arr 保证只有一项处于编辑状态

  // 上一个编辑的项
  const findLast = state.arr[
    cloneText.value.parent_index
  ]?.subtitle_text_block.find((ele) => ele.id == cloneText.value.item.id);

  if (!!findLast) {
    if (!findLast.text.trim()) {
      message.warning("文本内容不能为空!");
      findLast.text = cloneText.value.item.text;
    }
    findLast.isShow = false;
  }
  // 当前编辑的项
  item.isShow = true;
  cloneText.value = {
    item: JSON.parse(JSON.stringify(item)),
    parent_index,
  };

  nextTick(() => {
    // 获取焦点
    const dom = document.getElementById(`textarea_${item.id}`);
    !!dom && dom.focus();
  });
};

// 完成编辑
const editEd = (item) => {
  if (!item.text.trim()) {
    message.warning("文本内容不能为空!");
    item.text = cloneText.value.item.text;
  }
  item.isShow = false;
};

// 组件emit修改标题
const update = (data) => {
  const find = state.arr.find((item) => item.id === data.id);
  find && Object.assign(find, data);
};

// 删除某项
const deleteItem = (id) => {
  if (state.arr.length == 1) {
    message.warning("至少需要保留一组数据!");
    return;
  }
  const index = state.arr.findIndex((item) => item.id == id);
  index != -1 && state.arr.splice(index, 1);
};

// 选择导入的数据
const importData = computed(() => {
  const selectData = state.arr.filter((ele) => ele?.selected);
  return selectData;
});

// 进行导入
const submit = async () => {
  // 正在编辑的项
  const findLast = state.arr[
    cloneText.value.parent_index
  ]?.subtitle_text_block.find((ele) => ele.id == cloneText.value.item.id);
  if (!!findLast) {
    if (!findLast.text.trim()) {
      findLast.text = cloneText.value.item.text;
    }
    findLast.isShow = false;
  }


    // 导入视频组 或者 全局文本需要获取音频的情况下, 并且不是脚本使用
    if ((props.type == 0 || props.initData?.type == "title") && !props.isScript) {
    console.log(importData.value, '选择勾选的数据');

    const str = importData.value.map(ele => ele.subtitle_text_block.map(i => i.text)).flat().join('')

    console.log(str, '所有的文本');

    try {
      const res = await utils.textConfigGet({
        number: str.length
      })
      // 查询积分, 积分不足则走不到这一步
      // 获取积分消耗提示内容
      const content = utils.useText(res)
      try {
        // 确认消耗
        await utils.kd({ content,res })
      } catch (error) {
        return
      }
    } catch (error) {
      // 打开充值, 接着打开点数购买
      vipVisible.value = true
      vipModalRef.value && vipModalRef.value.openBuyVisible()
      emit("updateStep", 1);
      return
    }
  }


  // 进入下一个步骤
  emit("updateStepThree", {
    title: "数据导入中...",
    btn_text: "数据正在导入中...",
    loading: true,
  });
  nextTick(() => {
    emit("updateStep", 2);
    // 如果是脚本使用则直接返回
    if (props.isScript) {
      emit("emitArr", state.arr);
      return;
    }
    // 0-分镜头文本，1-全局文本
    if (props.type == 0) {
      setTemplateData();
    } else {
      setGlobalData();
    }
  });
};

// 获得字体大小转换的比例
const scaleData = computed(() => {
  const { showHeight, showWidth } = store.state.shotstack.VideoMashup;
  return resetXY(showHeight, showWidth);
});

// 从仓库中拿到各镜头组数据
const resource_data = computed(() => {
  return store.state.shotstack.VideoMashup.resource_data;
});

// 导入视频组标题数据
const setTitle = async (fnData) => {
  // 全局标题数据
  const cloneGlobal_text_config = JSON.parse(
    JSON.stringify(VideoMashup.value.global_text_config)
  );

  // 需要导入的数据

  const importTitle = addNewlineAfterPunctuation(
    fnData.cloneImportData[fnData.index].title
  );
  // const importSubtitle = addNewlineAfterPunctuation(
  //   fnData.cloneImportData[fnData.index].subtitle
  // );

  // const subtitle_fontsieze = 14; // 副标题字体大小

  // 获取一个基础数据, 取他的配置
  const baseTarget = cloneGlobal_text_config.configs[0][0];
  // 固定在中心点的x
  const showX = sizeData.value.draggableWidth / xLocation;
  // debugger
  const titleFS = baseTarget.font_size / scaleData.value.scaleWidth;
  // const subtitleFS = subtitle_fontsieze / scaleData.value.scaleWidth;
  // debugger
  const newTextWidth = await getTextWidthUsingCanvas(
    importTitle,
    titleFS,
    baseTarget.font_family
  );
  // const subtitleWidth = await getTextWidthUsingCanvas(
  //   importSubtitle,
  //   subtitleFS,
  //   baseTarget.font_family
  // );

  // 全局的换行数量
  // let lineFeedNum = importTitle.match(/\n/g)?.length || 0;
  // 随机的两组标题花字样式
  const preset_styles_config_Arr = getFlower();
  return [
    {
      ...JSON.parse(JSON.stringify(baseTarget)),
      color: preset_styles_config_Arr[0].fontcolor,
      text: importTitle,
      showX,
      x: showX - newTextWidth / 2,
      id: nanoid(),
      y: sizeData.value.draggableHeight / titleHeightratio,
      preset_styles_config: {
        box: preset_styles_config_Arr[0].box,
        type: 1,
        fontcolor: preset_styles_config_Arr[0].fontcolor || "",
        bordercolor: preset_styles_config_Arr[0].bordercolor || "",
        id: preset_styles_config_Arr[0].id || "",
        borderw: preset_styles_config_Arr[0].borderw || "",
        boxcolor: preset_styles_config_Arr[0].boxcolor || "",
        box_color_alpha: preset_styles_config_Arr[0].box_color_alpha || "",
        boxborderw: preset_styles_config_Arr[0].boxborderw || "",
        // boxradius: preset_styles_config_Arr[0].boxradius || "",
      },
    },
    // {
    //   ...JSON.parse(JSON.stringify(baseTarget)),
    //   color: preset_styles_config_Arr[1].fontcolor,
    //   text: importSubtitle,
    //   showX,
    //   x: showX - subtitleWidth / 2,
    //   id: nanoid(),
    //   font_size: subtitle_fontsieze,
    //   y:
    //     sizeData.value.draggableHeight / textSubtitleHeight +
    //     lineFeedNum * yOffset,
    //   preset_styles_config: {
    //     box: preset_styles_config_Arr[1].box,
    //     type: 1,
    //     fontcolor: preset_styles_config_Arr[1].fontcolor || "",
    //     bordercolor: preset_styles_config_Arr[1].bordercolor || "",
    //     id: preset_styles_config_Arr[1].id || "",
    //     borderw: preset_styles_config_Arr[1].borderw || "",
    //     boxcolor: preset_styles_config_Arr[1].boxcolor || "",
    //     box_color_alpha: preset_styles_config_Arr[1].box_color_alpha || "",
    //     boxborderw: preset_styles_config_Arr[1].boxborderw || "",
    //     // boxradius: preset_styles_config_Arr[1].boxradius || "",
    //   },
    // },
  ];

  // // 过滤掉空的项, 插入主标题和副标题
  // const cloneData = JSON.parse(JSON.stringify(fnData.titleData.text_config[0]))
  // fnData.titleData.text_config = fnData.titleData.text_config.filter(ele => ele.text.trim() != '')
  // const titleFontSize = +cloneData.font_size / scaleData.value.scaleWidth
  // // debugger
  // const importTitle = addNewlineAfterPunctuation(fnData.cloneImportData[fnData.index].title)
  // const importSubtitle = addNewlineAfterPunctuation(fnData.cloneImportData[fnData.index].subtitle)
  // // 字体大小
  // const subtitleFS = fnData.subtitle_fontsieze / scaleData.value.scaleWidth

  // const titleWidth = await getTextWidthUsingCanvas(importTitle, titleFontSize, cloneData.font_family);
  // const subtitleWidth = await getTextWidthUsingCanvas(importSubtitle, subtitleFS, cloneData.font_family);

  // // 添加到全局标题

  // // 添加主标题
  // fnData.titleData.text_config.push({
  //     ...JSON.parse(JSON.stringify(cloneData)),
  //     text: importTitle,
  //     x: cloneData.showX - (titleWidth / 2),
  //     y: sizeData.value.draggableHeight / titleHeightratio,
  //     id: nanoid()
  // })

  // // 全局标题的换行数量
  // let lineFeedNum = (importTitle.match(/\n/g)?.length || 0)
  // // 添加副标题
  // fnData.titleData.text_config.push({
  //     ...JSON.parse(JSON.stringify(cloneData)),
  //     text: importSubtitle,
  //     x: cloneData.showX - (subtitleWidth / 2),
  //     // y: sizeData.value.draggableHeight / textSubtitleHeight,
  //     y: sizeData.value.draggableHeight / textSubtitleHeight + (lineFeedNum * yOffset),
  //     font_size: fnData.subtitle_fontsieze,
  //     id: nanoid()
  // })
};

// 存放左侧视频组数据
const setTemplateData = async () => {
  // 需要导入的数据
  state.getVoiceLoding = true;
  let cloneImportData = JSON.parse(JSON.stringify(importData.value));
  let titleData = JSON.parse(JSON.stringify(importData.value));
  const subtitle_fontsieze = 14; // 副标题字体大小

  try {
    let global_text_config = [];

    // 最大长度的那条
    let maxLength = 0;

    // 获取最大长度的那条
    cloneImportData.forEach((item) => {
      if (item.subtitle_text_block.length > maxLength) {
        maxLength = item.subtitle_text_block.length;
      }
    });

    for (let index = 0; index < cloneImportData.length; index++) {
      // 处理所有的标题
      let TitleArr = await setTitle({
        titleData: resource_data.value[index],
        subtitle_fontsieze,
        cloneImportData,
        index,
      });
      global_text_config.push(TitleArr);
    }

    let templateData = [];

    for (let index = 0; index < maxLength; index++) {
      const arr = cloneImportData.map((ele) => {
        return ele.subtitle_text_block.filter((sub, sub_index) => {
          return sub_index == index;
        });
      });
      templateData[index] = [...arr.flat()];
    }

    console.log(templateData, "templateData");
    console.log(global_text_config, "global_text_config");

    let sub;
    let ttsData;

    for (let index = 0; index < templateData.length; index++) {
      if (!!resource_data.value[index]) {
        for (
          let subIndex = 0;
          subIndex < templateData[index].length;
          subIndex++
        ) {
          // 导入计算x轴 所需要的字体大小
          sub = JSON.parse(
            JSON.stringify(resource_data.value[index].tts_config[0].subtitle[0])
          );
          // 基础的 tts配置
          ttsData = JSON.parse(
            JSON.stringify(resource_data.value[index].tts_config[0])
          );
          const font_size = +sub.font_size / scaleData.value.scaleWidth;
          // 需要导入的这一项, 文本
          const importItem = templateData[index]?.[subIndex];

          // 标点切割
          let subTitleArr = splitTextAndRemoveCommas(importItem.text);
          console.log(subTitleArr, "subTitleArrsubTitleArrsubTitleArr");
          // 切割之后 将切割项 处理成 subtitle数组
          for (let sub_item = 0; sub_item < subTitleArr.length; sub_item++) {
            const textWidth = await getTextWidthUsingCanvas(
              subTitleArr[sub_item],
              font_size,
              sub.font_family
            );
            subTitleArr[sub_item] = {
              ...JSON.parse(JSON.stringify(sub)),
              text: subTitleArr[sub_item],
              ssml: "<speak>" + subTitleArr[sub_item] + "</speak>",
              subtitle_id: nanoid(),
              x: sub.showX - textWidth / 2,
              y: sizeData.value.draggableHeight / subtitleHeightratio,
              material_path: "",
              audio_url: "",
              duration: "",
            };
          }
          const tts_id = nanoid();
          // 先直接push, 后面过滤一下空的项
          let ssmlContent = subTitleArr
            .map(
              (ele) =>
                `<speak subId="${ele.subtitle_id}" tts_id="${tts_id}">${ele.text}</speak>`
            )
            .join("");

          resource_data.value[index].tts_config.push({
            ...JSON.parse(JSON.stringify(ttsData)),
            tts_id,
            tab_id: "text",
            subtitle: subTitleArr,
            showSubtitle: true,
            showVoice: true,
            ssmlContent,
          });
        }
      } else {
        // 创建视频组 进行导入
        const font_size = sub.font_size / scaleData.value.scaleWidth;
        const base_template_data = base_data();
        let useIndex = index;
        base_template_data.name = `视频组${++useIndex}`;
        for (
          let subIndex = 0;
          subIndex < templateData[index].length;
          subIndex++
        ) {
          // 需要导入的这一项, 文本
          const importItem = templateData[index]?.[subIndex];

          const tts_id = nanoid();
          // 标点切割
          const subTitleArr = splitTextAndRemoveCommas(importItem.text);
          // 切割之后 将切割项 处理成 subtitle数组
          for (let sub_item = 0; sub_item < subTitleArr.length; sub_item++) {
            const textWidth = await getTextWidthUsingCanvas(
              subTitleArr[sub_item],
              font_size,
              sub.font_family
            );
            subTitleArr[sub_item] = {
              ...JSON.parse(JSON.stringify(sub)),
              text: subTitleArr[sub_item],
              ssml: "<speak>" + subTitleArr[sub_item] + "</speak>",
              subtitle_id: nanoid(),
              x: sub.showX - textWidth / 2,
              y: sizeData.value.draggableHeight / subtitleHeightratio,
              material_path: "",
              audio_url: "",
              duration: "",
            };
          }

          // 先直接push, 后面过滤一下空的项
          const ssmlContent = subTitleArr
            .map(
              (ele) =>
                `<speak subId="${ele.subtitle_id}" tts_id="${tts_id}">${ele.text}</speak>`
            )
            .join("");

          base_template_data.tts_config.push({
            ...JSON.parse(JSON.stringify(ttsData)),
            tts_id,
            tab_id: "text",
            subtitle: subTitleArr,
            showSubtitle: true,
            showVoice: true,
            ssmlContent,
          });
        }
        /**
         * 新增的, 时长设置修改为随音频
         */
        base_template_data.time_strategy = {
          // 时长设置=>决定镜头组以哪个元素的时长为准
          type: 1, // 时长类型设置：（0-视频原始时长，1-随音频，视频自动变速 ，2-随音频，视频智能截取 ，3-固定时长，智能去重）
          fixed_time: 3000, //类型为 3-固定时长，智能去重 时有效
        };
        resource_data.value.push(base_template_data);
      }
      if (!!resource_data.value[index]) {
        // 过滤出空的项
        resource_data.value[index].tts_config = resource_data.value[
          index
        ].tts_config.filter((ele) => {
          if (ele.subtitle.length > 1) {
            return true;
          } else {
            if (ele.tab_id == "audio") return true;
            return ele?.subtitle?.every(
              (i) => !!i.text.trim() && i.text.trim() !== "\n"
            );
          }
        });
      }
    }

    console.log(resource_data.value, "修改之后的数据");

    // 过滤掉空项
    if (global_text_config.length > 1) {
      global_text_config = global_text_config.filter((ele) => {
        return ele.some((i) => i.text.trim() && i.text.trim() != "\n");
      });
    }

    console.log(global_text_config, "全局标题数据");

    // 获取视频组音频数据
    console.log(resource_data.value, "获取音频之后");

    await getAllTemplateAudio(resource_data.value);

    // TODO 修改导入的标题为全局标题

    VideoMashup.value.global_text_config.type = 1;
    console.log(global_text_config, "导入全局的标题数据");
    VideoMashup.value.global_text_config.configs.push(...global_text_config);
    VideoMashup.value.global_text_config.type = 1;
    if (VideoMashup.value.global_text_config.configs.length > 1) {
      VideoMashup.value.global_text_config.configs =
        VideoMashup.value.global_text_config.configs.filter((ele) => {
          return ele.some((i) => i.text.trim() && i.text.trim() != "\n");
        });
    }
    VideoMashup.value.resource_data = resource_data.value;
    store.dispatch("SetVideoMashup", VideoMashup.value);

    // 存储全局标题数据

    state.getVoiceLoding = false;
    emit("updateStepThree", {
      title: "数据导入成功!",
      btn_text: "关闭",
      loading: false,
    });
    nextTick(() => {
      message.success(`数据导入成功！`);
    });
  } catch (error) {
    state.getVoiceLoding = false;
    emit("updateStepThree", {
      title: "数据导入失败!",
      btn_text: "关闭",
      loading: false,
    });
  }
};

// 将所有视频组的时长设置 改为原始时长
const resetTime_strategy = () => {
  VideoMashup.value.resource_data.forEach((ele) => {
    ele.material_list.forEach((item) => {
      // 将图片设置为 3秒, 视频设置为原始时长
      if (ele.time_strategy != 0 && ele.time_strategy.type != 3) {
        ele.time_strategy.type = 0;
        if (item.scene_type == "image") {
          item.end_time = 3000;
        } else {
          item.end_time = +item.material_duration;
        }
      }
    });
  });
};

// 存放右侧全局视频组的数据
const setGlobalData = async () => {
  state.getVoiceLoding = true;
  // 需要导入的数据
  const cloneImportData = JSON.parse(JSON.stringify(importData.value));
  try {
    // 全局的标题和字幕数据
    let cloneGlobal_text_config;
    let cloneGlobal_tts_config;
    if (props.initData != null) {
      if (props.initData?.type == "tts") {
        cloneGlobal_tts_config = JSON.parse(
          JSON.stringify(props.initData?.data)
        );
        cloneGlobal_text_config = JSON.parse(
          JSON.stringify(VideoMashup.value.global_text_config)
        );
      } else if (props.initData?.type == "title") {
        cloneGlobal_text_config = JSON.parse(
          JSON.stringify(props.initData?.data)
        );
        cloneGlobal_tts_config = JSON.parse(
          JSON.stringify(VideoMashup.value.global_tts_config)
        );
      }
    } else {
      cloneGlobal_text_config = JSON.parse(
        JSON.stringify(VideoMashup.value.global_text_config)
      );
      cloneGlobal_tts_config = JSON.parse(
        JSON.stringify(VideoMashup.value.global_tts_config)
      );
    }

    let text_ttsData = cloneGlobal_tts_config.configs.filter(
      (item) => item.tab_id == "text"
    );
    const audio_ttsData = cloneGlobal_tts_config.configs.filter(
      (item) => item.tab_id == "audio"
    );

    // 最大长度的那条
    let maxLength = 0;

    // 获取最大长度的那条
    cloneImportData.forEach((item) => {
      if (item.subtitle_text_block.length > maxLength) {
        maxLength = item.subtitle_text_block.length;
      }
    });
    let templateData = [];

    for (let index = 0; index < maxLength; index++) {
      const arr = cloneImportData.map((ele) => {
        return ele.subtitle_text_block.filter((sub, sub_index) => {
          return sub_index == index;
        });
      });
      templateData[index] = [...arr.flat()];
    }

    // 全局字幕 - 取第一项作为基础数据项
    const text_subtile = text_ttsData?.[0]?.subtitle?.[0];
    for (let index = 0; index < templateData.length; index++) {
      const font_size = +text_subtile?.font_size / scaleData.value.scaleWidth;

      for (
        let subIndex = 0;
        subIndex < templateData[index].length;
        subIndex++
      ) {
        // 需要导入的数据项
        // 需要导入的这一项, 文本
        const importItem = templateData[index]?.[subIndex];
        // 标点切割
        const subTitleArr = splitTextAndRemoveCommas(importItem.text);
        // 切割之后 将切割项 处理成 subtitle数组
        for (let sub_item = 0; sub_item < subTitleArr.length; sub_item++) {
          const sub = JSON.parse(JSON.stringify(text_ttsData[0].subtitle[0]));
          const textWidth = await getTextWidthUsingCanvas(
            subTitleArr[sub_item],
            font_size,
            sub.font_family
          );
          subTitleArr[sub_item] = {
            ...JSON.parse(JSON.stringify(sub)),
            text: subTitleArr[sub_item],
            ssml: "<speak>" + subTitleArr[sub_item] + "</speak>",
            subtitle_id: nanoid(),
            x: sub.showX - textWidth / 2,
            y: sizeData.value.draggableHeight / subtitleHeightratio,
            material_path: "",
            audio_url: "",
            duration: "",
          };
        }

        // 直接push 一个tts_config, 最后清空空的tts_config
        const tts_data = JSON.parse(JSON.stringify(text_ttsData[0]));
        const tts_id = nanoid();
        text_ttsData.push({
          ...tts_data,
          subtitle: subTitleArr,
          tts_id,
          tab_id: "text",
          showSubtitle: true,
          showVoice: true,
          ssmlContent: subTitleArr
            .map(
              (ele) =>
                `<speak subId="${ele.subtitle_id}" tts_id="${tts_id}">${ele.text}</speak>`
            )
            .join(""),
        });
      }
    }

    // 处理全局字幕导入
    for (let index = 0; index < cloneImportData.length; index++) {
      // const font_size = +text_subtile?.font_size / scaleData.value.scaleWidth;
      // 处理每一项的全局标题
      //
      const importTitle = addNewlineAfterPunctuation(
        cloneImportData[index].title
      );
      // const importSubtitle = addNewlineAfterPunctuation(
      //   cloneImportData[index].subtitle
      // );
      // const subtitle_fontsieze = 14; // 副标题字体大小

      // 获取一个基础数据, 取他的配置
      const baseTarget = cloneGlobal_text_config.configs[0][0];
      // 固定在中心点的x
      const showX = sizeData.value.draggableWidth / xLocation;
      // debugger
      const titleFS = baseTarget.font_size / scaleData.value.scaleWidth;
      // const subtitleFS = subtitle_fontsieze / scaleData.value.scaleWidth;
      // debugger
      const newTextWidth = await getTextWidthUsingCanvas(
        importTitle,
        titleFS,
        baseTarget.font_family
      );
      // const subtitleWidth = await getTextWidthUsingCanvas(
      //   importSubtitle,
      //   subtitleFS,
      //   baseTarget.font_family
      // );

      // 全局的换行数量
      // let lineFeedNum = importTitle.match(/\n/g)?.length || 0;
      // let subTitleFeedNum = (importSubtitle.match(/\n/g)?.length || 0) * 1.5
      // 先push进去, 最后再去除空项
      // 随机的两组标题花字样式
      const preset_styles_config_Arr = getFlower();

      cloneGlobal_text_config.configs.push([
        {
          ...JSON.parse(JSON.stringify(baseTarget)),
          color: preset_styles_config_Arr[0].fontcolor,
          text: importTitle,
          showX,
          x: showX - newTextWidth / 2,
          id: nanoid(),
          y: sizeData.value.draggableHeight / titleHeightratio,
          preset_styles_config: {
            box: preset_styles_config_Arr[0].box,
            type: 1,
            fontcolor: preset_styles_config_Arr[0].fontcolor || "",
            bordercolor: preset_styles_config_Arr[0].bordercolor || "",
            id: preset_styles_config_Arr[0].id || "",
            borderw: preset_styles_config_Arr[0].borderw || "",
            boxcolor: preset_styles_config_Arr[0].boxcolor || "",
            box_color_alpha: preset_styles_config_Arr[0].box_color_alpha || "",
            boxborderw: preset_styles_config_Arr[0].boxborderw || "",
            // boxradius: preset_styles_config_Arr[0].boxradius || "",
          },
        },
        // {
        //   ...JSON.parse(JSON.stringify(baseTarget)),
        //   color: preset_styles_config_Arr[1].fontcolor,
        //   text: importSubtitle,
        //   showX,
        //   x: showX - subtitleWidth / 2,
        //   id: nanoid(),
        //   font_size: subtitle_fontsieze,
        //   y:
        //     sizeData.value.draggableHeight / textSubtitleHeight +
        //     lineFeedNum * yOffset,
        //   preset_styles_config: {
        //     type: 1,
        //     box: preset_styles_config_Arr[1].box,
        //     fontcolor: preset_styles_config_Arr[1].fontcolor || "",
        //     bordercolor: preset_styles_config_Arr[1].bordercolor || "",
        //     id: preset_styles_config_Arr[1].id || "",
        //     borderw: preset_styles_config_Arr[1].borderw || "",
        //     boxcolor: preset_styles_config_Arr[1].boxcolor || "",
        //     box_color_alpha: preset_styles_config_Arr[1].box_color_alpha || "",
        //     boxborderw: preset_styles_config_Arr[1].boxborderw || "",
        //     // boxradius: preset_styles_config_Arr[1].boxradius || "",
        //   },
        // },
      ]);
    }

    // 过滤掉空项
    if (cloneGlobal_text_config.configs.length > 1) {
      cloneGlobal_text_config.configs = cloneGlobal_text_config.configs.filter(
        (ele) => {
          return ele.some((i) => i.text.trim() && i.text.trim() != "\n");
        }
      );
    }

    // 过滤掉空的tts数据
    if (text_ttsData.length > 1) {
      text_ttsData = text_ttsData.filter((ele) => {
        if (ele.subtitle.length > 1) {
          return true;
        } else {
          if (ele.tab_id == "audio") return true;
          return ele?.subtitle?.every(
            (i) => !!i.text.trim() && i.text.trim() !== "\n"
          );
        }
      });
    }
    if (!props.isQuanJU) {
      VideoMashup.value.global_text_config.type = 1;
      VideoMashup.value.global_tts_config.type = 1;
      // 获取全局每个tts下面的 subtitle的音频
      await getGlobalSubtitleAudio(text_ttsData);

      // debugger

      VideoMashup.value.global_tts_config.configs = [
        ...text_ttsData,
        ...audio_ttsData,
      ];

      VideoMashup.value.global_text_config.configs = [
        ...cloneGlobal_text_config.configs,
      ];

      resetTime_strategy();

      store.dispatch("SetVideoMashup", VideoMashup.value);
      emit("updateStepThree", {
        title: "数据导入成功!",
        btn_text: "关闭",
        loading: false,
      });
      nextTick(() => {
        message.success(`数据导入成功！`);
      });
      state.getVoiceLoding = false;
      return;
    }

    if (props.initData?.type == "tts") {
      // 热更新抽屉中的tts的数据, 修改全局标题的数据
      cloneGlobal_tts_config.configs = [...text_ttsData, ...audio_ttsData];
      emit("updateAiData", {
        global_tts_config: cloneGlobal_tts_config,
      });
      VideoMashup.value.global_text_config.type = 1;
      VideoMashup.value.global_text_config.configs = [
        ...cloneGlobal_text_config.configs,
      ];
      store.dispatch("SetVideoMashup", VideoMashup.value);
      state.getVoiceLoding = false;
      emit("updateStepThree", {
        title: "数据导入成功!",
        btn_text: "关闭",
        loading: false,
      });
      nextTick(() => {
        message.success(`数据导入成功！`);
      });
    } else if (props.initData?.type == "title") {
      // 热更新抽屉中的标题数据, 修改全局tts的数据
      emit("updateAiData", {
        global_text_config: cloneGlobal_text_config,
      });
      // 获取全局每个tts下面的 subtitle的音频
      await getGlobalSubtitleAudio(text_ttsData);
      // alert('获取tts的音频成功!')
      console.log(text_ttsData, "text_ttsData");

      VideoMashup.value.global_tts_config.type = 1;
      VideoMashup.value.global_tts_config.configs = [
        ...text_ttsData,
        ...audio_ttsData,
      ];
      resetTime_strategy();

      store.dispatch("SetVideoMashup", VideoMashup.value);
      state.getVoiceLoding = false;
      emit("updateStepThree", {
        title: "数据导入成功!",
        btn_text: "关闭",
        loading: false,
      });
      nextTick(() => {
        message.success(`数据导入成功！`);
      });
    }
  } catch (error) {
    state.getVoiceLoding = false;
    emit("updateStepThree", {
      title: "数据导入失败!",
      btn_text: "关闭",
      loading: false,
    });
  }
};

// 改变loding状态
const changeSpinning = (flage) => {
  state.spinning = flage;
};
// 初始获取数据
const setData = (data) => {
  data.arr?.forEach((item) => {
    !item?.id && (item.id = nanoid());
    item.selected = true;
    item?.subtitle_text_block &&
      (item.subtitle_text_block = item.subtitle_text_block.map((i, index) => {
        return {
          text: i,
          id: item.id + index,
          isShow: false,
        };
      }));
  });
  console.log(data, "data数据");
  state.arr = data.arr;
  //   state.arr.push(...data.arr);
  // props.type = data.types
  console.log(state.arr, "编辑赋值之后的数据");
};
const importLoading = computed(() => {
  return state.arr?.some((ele) => ele?.title && !ele?.subtitle_text_block);
});
// 没有数据, 并且不在loding, 禁用头部的选择导入按钮
const disabled = computed(() => {
  console.log(state.arr.length, "len", state.spinning, "sp");
  return !state.arr.length && !state.spinning;
});

const spinningState = computed(() => {
  return {
    spinning: state.spinning,
    getVoiceLoding: state.getVoiceLoding,
  };
});

// 清空数据
const clearData = () => {
  // props.type = ''
  // state.getVoiceLoding = false
};
const disImportClick = computed(() => {
  return state.arr?.some((ele) => ele.title && !ele.subtitle_text_block);
});
defineExpose({
  changeSpinning,
  setData,
  clearData,
  disabled,
  spinningState,
  // disabled: (state.arr.length || state.spinning) ? false : true
});
</script>

<template>
  <div class="ImportVideogroupData">
    <!-- {{ props.type + 'type' }} -->
    <div class="split_title_box">
      <h2 class="title_text">
        选择导入({{ props.type == 0 ? "分镜头文本" : "全局文本" }})
      </h2>
    </div>

    <a-spin :spinning="state.spinning" style="width: 100%" tip="正在为您生成数据，请稍后" />
    <div @click="i.selected = !i.selected" class="videogroup_data_item" :class="{
      active: i.selected,
    }" v-for="(i, index) in state.arr" :key="i.id">
      <a-checkbox class="checkBox" v-model:checked="i.selected"></a-checkbox>
      <div class="title_box">
        <a-popconfirm title="确定删除此项吗？" ok-text="确定" cancel-text="取消" @confirm="deleteItem(i.id)">
          <a-button class="btn" @click.stop="() => { }">
            <DeleteOutlined></DeleteOutlined>删除
          </a-button>
        </a-popconfirm>
        <div class="min_title">
          <span class="number">No.{{ index + 1 }}</span>
          <span class="min_title_text">{{ i.title }}</span>
          <span class="edit_target" @click.stop="editTitle(i)">
            <EditOutlined />
          </span>
        </div>
        <!-- <div class="subhead">
          <span class="subhead_text">{{ i.subtitle }}</span>
        </div> -->
      </div>
      <div class="content">
        <a-spin :spinning="i.title && !i.subtitle_text_block">
          <div v-for="(item, item_index) in i.subtitle_text_block" class="content_item" :key="item.id">
            <div class="textarea_box" v-if="item.isShow">
              <a-textarea v-model:value="item.text" placeholder="请输入文本内容" allowClear showCount
                :id="'textarea_' + item.id" :maxlength="500" style="resize: none" :auto-size="{
                  minRows: 3,
                  maxRows: 7,
                }">
              </a-textarea>
              <!-- <a-button class="btn importText" style="" type="link" size="small" @click.stop="
                openMaterial({
                  index,
                  item_index,
                })
                ">
                文案导入
              </a-button> -->
              <a-button class="btn edited" style="" type="link" size="small" @click.stop="editEd(item)">
                完成编辑
              </a-button>
            </div>

            <div class="content_text" v-else @click.stop="showTextArea(item, item_index, index)">
              <cu-icon type="icon-dian" v-show="!state.isHover" contenteditable="false"></cu-icon>
              {{ item.text }}
            </div>
          </div>
        </a-spin>
      </div>
    </div>

    <a-button v-show="state.arr.length" :disabled="!importData.length || disImportClick" :loading="state.getVoiceLoding"
      type="primary" @click="submit" style="width: 100%">
      导入数据
    </a-button>
  </div>

  <!-- 编辑标题弹窗 -->
  <EditTitleComponent ref="EditTitleComponentRef" @update="update"></EditTitleComponent>

  <ChooseMaterial :isClip="true" material_type="text" :multiple="true" :visible="state.materiallibraryShow"
    @close="closeChooseMaterial($event, 'material_type')" />
      <!-- 充值弹窗 -->
  <vipModal ref="vipModalRef" :visible="vipVisible" @close="vipVisible = false"></vipModal>

</template>

<style lang="less" scoped>
.ImportVideogroupData {
  // padding: 15px;
  // border: 1px solid #e0e0e0;
  // border-radius: 10px;

  // 分割的小标题
  .split_title_box {
    margin: 20px 0;

    .title_text {
      font-size: 16px;
      font-weight: 900;
      margin: 0;
    }
  }

  .title {
    font-size: 14px;
    margin: 0;
  }

  .content {
    padding: 8px 10px;
    border: 1px solid #e0e0e0;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    gap: 10px;

    .content_item {
      .content_text {
        cursor: pointer;
      }
    }

    // textarea 文案导入布局
    .textarea_box {
      position: relative;
      width: 100%;
      margin: 15px 0;

      .btn {
        opacity: 0;
        transition: all 0.3s;
        position: absolute;
        width: 20px;
        font-size: 12px;
      }

      .importText {
        right: 90px;
        top: -23px;
      }

      .edited {
        right: 35px;
        top: -23px;
      }

      &:hover {
        .btn {
          opacity: 1;
        }
      }
    }
  }

  .videogroup_data_item {
    display: flex;
    flex-direction: column;
    margin: 20px 0;
    border: 1px solid #e0e0e0;
    padding: 15px;
    padding-top: 30px;
    border-radius: 10px;
    position: relative;
    cursor: pointer;

    &.active {
      // background-color: var(--ss-primary-3);
      border-color: var(--ss-primary-5);
      // color: #fff;
    }

    .checkBox {
      position: absolute;
      top: 7px;
      left: 14px;
    }

    .title_box {
      display: flex;
      flex-direction: column;
      position: relative;

      .btn {
        position: absolute;
        top: 0;
        right: 0;
        padding: 0 10px;
        height: 25px;
        font-size: 14px;
      }

      .min_title {
        font-weight: 900;
        margin-bottom: 10px;

        .number {
          margin-right: 5px;
        }

        .edit_target {
          cursor: pointer;
          margin-left: 5px;

          &:hover {
            color: var(--ss-primary-color);
          }
        }
      }

      .subhead {
        margin-bottom: 10px;
      }
    }
  }
}
</style>
